﻿/*************************************************************************
 * Created by OhZee Creative, LLC
 * 2013
 * This code is licensed under Microsoft Public License (Ms-PL)
 * http://opensource.org/licenses/ms-pl
 * http://ozframework.codeplex.com/
 *************************************************************************/

namespace OhZeeCreative.WindowsPhone
{
    using System;
    using System.Diagnostics;
    using Microsoft.Phone.Shell;

    public class IdleDetectionManager
    {
        private object countLock = new object();
        private int count;

		public bool DisableUserIdleDetection { get; set; }

        public void Push()
        {
            lock (this.countLock)
            {
                this.count++;
                Debug.WriteLine("IdleDetectionManager Push: " + this.count.ToString());

                if (this.count == 1 && this.DisableUserIdleDetection)
                {
                    PhoneApplicationService.Current.UserIdleDetectionMode = IdleDetectionMode.Disabled;
                    Debug.WriteLine("IdleDetectionManager idle=DISABLED");
                }                                    
            }
        }

        public void Pop()
        {
            lock (this.countLock)
            {
                Debug.Assert(this.count > 0);

                if (this.count > 0)
                {
                    this.count--;
                    Debug.WriteLine("IdleDetectionManager Pop: " + this.count.ToString());

                    if (this.count == 0)
                    {
                        try
                        {
                            Debug.WriteLine("IdleDetectionManager idle=ENABLED");
                            PhoneApplicationService.Current.UserIdleDetectionMode = IdleDetectionMode.Enabled;
                        }
                        catch (InvalidOperationException)
                        {
                            // This exception is expected in the current release.
                        }
                    }
                }
            }
        }
                
    }
}
